package app.core;

import app.config.Config;
import com.gitee.feizns.quickstart.easy.captcha.EasyCaptcha;
import com.gitee.feizns.quickstart.web.WebUtils;
import com.gitee.feizns.quickstart.web.ex.BadRequestException;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.wf.captcha.SpecCaptcha;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 验证码
 * @author feizns
 * @since 2025/11/6
 */
public class VerificationCode {

    /**
     * 验证码缓存（账号：验证码）
     */
    private static final Cache<String, String> cache = Caffeine.newBuilder().expireAfterWrite(Config.loginCaptchaValidMinutes(), TimeUnit.MINUTES).build();

    /**
     * 放置
     * @param account 帐户
     * @param code 验证码
     */
    public static void put(String account, String code) {
        cache.put(account, code);
    }

    /**
     * 验证
     * @param account 账号
     * @param code 验证码
     */
    public static void verify(String account, String code) {
        String cacheCode = cache.getIfPresent(account);
        if ( !Objects.equals(cacheCode, code) )
            throw new BadRequestException("验证码错误.");
        cache.invalidate(account);
    }

    /**
     * 生成图片验证码
     */
    public static String generateImageCaptcha() {
        SpecCaptcha captcha = EasyCaptcha.spec();
        VerificationCode.put(WebUtils.getReq().getSession().getId(), captcha.text().toLowerCase());
        return captcha.toBase64();
    }

    /**
     * 生成短信验证码
     * @param mobile 移动
     * @return {@link String }
     */
    public static String generateNumberCaptcha(String mobile) {
        String code = EasyCaptcha.number().text();
        VerificationCode.put(mobile, code);
        return code;
    }

}
